// 全局变量
let currentPage = 1;
const pageSize = 10;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initializePage();
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化页面
function initializePage() {
    // 加载系统统计信息
    loadSystemStats();
    
    // 加载文件列表
    loadFileList();
    
    // 加载搜索历史
    loadSearchHistory();
}

// 绑定事件监听器
function bindEventListeners() {
    // 文件上传表单提交
    const uploadForm = document.getElementById('upload-form');
    if (uploadForm) {
        uploadForm.addEventListener('submit', handleFileUpload);
    }
    
    // 搜索表单提交
    const searchForm = document.getElementById('search-form');
    if (searchForm) {
        searchForm.addEventListener('submit', handleSearch);
    }
    
    // 文件列表分页
    const prevBtn = document.getElementById('prev-page');
    const nextBtn = document.getElementById('next-page');
    
    if (prevBtn) {
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                loadFileList();
            }
        });
    }
    
    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            currentPage++;
            loadFileList();
        });
    }
    
    // 拖拽上传区域
    setupDragAndDrop();
}

// 设置拖拽上传
function setupDragAndDrop() {
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file');
    
    if (!dropZone || !fileInput) return;
    
    // 阻止默认拖拽行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });
    
    // 高亮拖拽区域
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
    });
    
    // 处理文件放下
    dropZone.addEventListener('drop', handleDrop, false);
    
    // 点击拖拽区域触发文件选择
    dropZone.addEventListener('click', () => {
        fileInput.click();
    });
    
    // 文件选择后触发上传
    fileInput.addEventListener('change', handleFileSelection);
}

// 阻止默认行为
function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

// 高亮拖拽区域
function highlight() {
    const dropZone = document.getElementById('drop-zone');
    if (dropZone) {
        dropZone.classList.add('dragover');
    }
}

// 取消高亮拖拽区域
function unhighlight() {
    const dropZone = document.getElementById('drop-zone');
    if (dropZone) {
        dropZone.classList.remove('dragover');
    }
}

// 处理文件放下
function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    handleFiles(files);
}

// 处理文件选择
function handleFileSelection(e) {
    const files = e.target.files;
    handleFiles(files);
}

// 处理文件
function handleFiles(files) {
    if (files.length > 0) {
        const fileInput = document.getElementById('file');
        const uploadForm = document.getElementById('upload-form');
        
        // 设置文件到表单
        fileInput.files = files;
        
        // 自动提交表单
        if (uploadForm) {
            uploadForm.dispatchEvent(new Event('submit'));
        }
    }
}

// 加载系统统计信息
function loadSystemStats() {
    fetch('/api/v1/system/stats')
        .then(response => response.json())
        .then(data => {
            if (data.files && data.vectors) {
                document.getElementById('total-files').textContent = data.files.total;
                document.getElementById('processed-files').textContent = data.files.processed;
                document.getElementById('failed-files').textContent = data.files.failed;
                document.getElementById('total-vectors').textContent = data.vectors.total_count;
            }
        })
        .catch(error => {
            console.error('加载系统统计信息失败:', error);
        });
}

// 加载文件列表
function loadFileList() {
    fetch(`/api/v1/files?page=${currentPage}&page_size=${pageSize}`)
        .then(response => response.json())
        .then(data => {
            if (data.files) {
                renderFileList(data.files);
                updatePagination(data.pagination);
            }
        })
        .catch(error => {
            console.error('加载文件列表失败:', error);
        });
}

// 渲染文件列表
function renderFileList(files) {
    const fileListBody = document.getElementById('file-list-body');
    if (!fileListBody) return;
    
    fileListBody.innerHTML = '';
    
    if (files.length === 0) {
        fileListBody.innerHTML = '<tr><td colspan="6">暂无文件</td></tr>';
        return;
    }
    
    files.forEach(file => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${file.filename}</td>
            <td>${formatFileSize(file.file_size)}</td>
            <td>${file.file_type}</td>
            <td>${file.status}</td>
            <td>${file.chunk_count}</td>
            <td>
                <button class="btn" onclick="viewFileDetail('${file.file_id}')">查看详情</button>
            </td>
        `;
        fileListBody.appendChild(row);
    });
}

// 更新分页信息
function updatePagination(pagination) {
    const pageInfo = document.getElementById('page-info');
    if (pageInfo && pagination) {
        pageInfo.textContent = `第 ${pagination.current_page} 页，共 ${pagination.total_pages} 页`;
    }
}

// 查看文件详情
function viewFileDetail(fileId) {
    window.location.href = `/files/${fileId}`;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 处理文件上传
function handleFileUpload(e) {
    e.preventDefault();
    
    const form = document.getElementById('upload-form');
    const formData = new FormData(form);
    
    // 显示上传进度
    showUploadProgress();
    
    fetch('/api/v1/files/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideUploadProgress();
        
        if (data.success) {
            showMessage('文件上传成功', 'success');
            // 重新加载文件列表和统计信息
            loadFileList();
            loadSystemStats();
            
            // 清空文件选择
            const fileInput = document.getElementById('file');
            if (fileInput) {
                fileInput.value = '';
            }
        } else {
            showMessage('文件上传失败: ' + (data.error || '未知错误'), 'error');
        }
    })
    .catch(error => {
        hideUploadProgress();
        showMessage('文件上传失败: ' + error.message, 'error');
    });
}

// 显示上传进度
function showUploadProgress() {
    const progress = document.getElementById('upload-progress');
    if (progress) {
        progress.classList.remove('hidden');
    }
}

// 隐藏上传进度
function hideUploadProgress() {
    const progress = document.getElementById('upload-progress');
    if (progress) {
        progress.classList.add('hidden');
    }
}

// 处理搜索
function handleSearch(e) {
    e.preventDefault();
    
    const queryInput = document.getElementById('search-query');
    const query = queryInput ? queryInput.value.trim() : '';
    
    if (!query) {
        showMessage('请输入搜索关键词', 'error');
        return;
    }
    
    // 显示搜索进度
    showSearchProgress();
    
    fetch('/api/v1/search', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            query: query,
            top_k: 10
        })
    })
    .then(response => response.json())
    .then(data => {
        hideSearchProgress();
        
        if (data.success) {
            renderSearchResults(data.results);
            showMessage(`找到 ${data.total_found} 个结果`, 'success');
        } else {
            showMessage('搜索失败: ' + (data.error || '未知错误'), 'error');
        }
    })
    .catch(error => {
        hideSearchProgress();
        showMessage('搜索失败: ' + error.message, 'error');
    });
}

// 显示搜索进度
function showSearchProgress() {
    const progress = document.getElementById('search-progress');
    if (progress) {
        progress.classList.remove('hidden');
    }
}

// 隐藏搜索进度
function hideSearchProgress() {
    const progress = document.getElementById('search-progress');
    if (progress) {
        progress.classList.add('hidden');
    }
}

// 渲染搜索结果
function renderSearchResults(results) {
    const resultsContainer = document.getElementById('search-results');
    if (!resultsContainer) return;
    
    resultsContainer.innerHTML = '';
    
    if (results.length === 0) {
        resultsContainer.innerHTML = '<p>未找到相关结果</p>';
        return;
    }
    
    results.forEach(result => {
        const resultItem = document.createElement('div');
        resultItem.className = 'result-item';
        resultItem.innerHTML = `
            <div class="result-header">
                <div class="result-filename">${result.filename}</div>
                <div class="result-score">相似度: ${result.score.toFixed(4)}</div>
            </div>
            <div class="result-content">${result.content}</div>
            <div class="result-meta">
                <span>文件ID: ${result.file_id}</span> | 
                <span>块索引: ${result.chunk_index}</span> | 
                <span>创建时间: ${new Date(result.created_time * 1000).toLocaleString()}</span>
            </div>
        `;
        resultsContainer.appendChild(resultItem);
    });
}

// 加载搜索历史
function loadSearchHistory() {
    fetch('/api/v1/search/history?limit=10')
        .then(response => response.json())
        .then(data => {
            if (data.history) {
                renderSearchHistory(data.history);
            }
        })
        .catch(error => {
            console.error('加载搜索历史失败:', error);
        });
}

// 渲染搜索历史
function renderSearchHistory(history) {
    const historyList = document.getElementById('search-history-list');
    if (!historyList) return;
    
    historyList.innerHTML = '';
    
    if (history.length === 0) {
        historyList.innerHTML = '<li>暂无搜索历史</li>';
        return;
    }
    
    history.forEach(item => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
            <div class="history-query">${item.query}</div>
            <div class="history-meta">
                <span>结果数: ${item.result_count}</span> | 
                <span>耗时: ${item.search_time.toFixed(3)}s</span> | 
                <span>${new Date(item.created_time).toLocaleString()}</span>
            </div>
        `;
        historyList.appendChild(listItem);
    });
}

// 显示消息
function showMessage(message, type) {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.className = `message message-${type}`;
    messageElement.textContent = message;
    
    // 添加样式
    messageElement.style.position = 'fixed';
    messageElement.style.top = '20px';
    messageElement.style.right = '20px';
    messageElement.style.padding = '10px 20px';
    messageElement.style.borderRadius = '4px';
    messageElement.style.color = 'white';
    messageElement.style.zIndex = '1000';
    messageElement.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)';
    
    if (type === 'success') {
        messageElement.style.backgroundColor = '#4a6741';
    } else {
        messageElement.style.backgroundColor = '#e74c3c';
    }
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageElement.parentNode) {
            messageElement.parentNode.removeChild(messageElement);
        }
    }, 3000);
}